import math
import threading

import numpy as np
import torch
from torch import nn

import d2l

max_degree = 40  # 多项式的最大阶数
n_train, n_test = 100, 100  # 训练数据集和测试数据集的大小
true_w = np.zeros(max_degree)  # 分配大量的空间
assert true_w.shape == (max_degree, )
true_w[0: 4] = np.array([5, 1.2, -3.4, 5.6])

features = np.random.normal(size=(n_train + n_test, 1))
np.random.shuffle(features)
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))
for i in range(max_degree):
    poly_features[:, i] /= math.gamma(i + 1)

labels = np.dot(poly_features, true_w)
assert labels.shape == (len(poly_features), )
labels += np.random.normal(scale=0.1, size=labels.shape)

true_w, features, poly_features, labels = [
    torch.tensor(x, dtype=torch.float32)
    for x in [true_w, features, poly_features, labels]
]

print('features[:2]:')
print(features[:2])
print(features.shape)
print()

print('poly_features[:2, :]:')
print(poly_features[:2, :])
print(poly_features.shape)
print()

print('labels[:2]')
print(labels[:2])
print(labels.shape)
print()


def async_train(train_features, test_features, train_labels, test_labels, num_epochs=400):
    loss = nn.MSELoss(reduction='none')
    input_shape = train_features.shape[-1]
    net = nn.Sequential(nn.Linear(input_shape, 1, bias=False))
    batch_size = min(10, train_labels.shape[0])
    train_iter = d2l.load_array((train_features, train_labels.reshape(-1, 1)), batch_size)
    test_iter = d2l.load_array((test_features, test_labels.reshape(-1, 1)), batch_size)
    trainer = torch.optim.SGD(net.parameters(), lr=0.01)

    animator = d2l.Animator(xlabel='epoch', ylabel='loss', yscale='log',
                            xlim=[1, num_epochs], ylim=[1e-3, 1e2],
                            legend=['train', 'test'])

    def thread_body():
        for epoch in range(num_epochs):
            print(f'training epoch[{epoch}/{num_epochs}]')
            d2l.train_epoch_ch3(net, train_iter, loss, trainer)
            if epoch == 0 or (epoch + 1) % 20 == 0:
                animator.add(epoch + 1, (d2l.evaluate_loss(net, train_iter, loss),
                                         d2l.evaluate_loss(net, test_iter, loss)))
        print('weight:', net[0].weight.data.numpy())

    threading.Thread(target=thread_body).start()


def run_normal():
    """模拟正常情况"""
    async_train(poly_features[:n_train, :4], poly_features[n_train:, :4], labels[:n_train], labels[n_train:])


def run_underfit():
    """模拟欠拟合"""
    async_train(poly_features[:n_train, :2], poly_features[n_train:, :2], labels[:n_train], labels[n_train:])


def run_overfit():
    """模拟过拟合"""
    async_train(poly_features[:n_train, :], poly_features[n_train:, :],
                labels[:n_train], labels[n_train:], num_epochs=1500)


# run_normal()
# run_underfit()
run_overfit()

d2l.plt.show()
